package openjdk.collections.map;

import java.util.*;
import java.util.stream.Collectors;

/**
 * Hash map 本身是无序的，不过也可以对其进行key或者 value的排序
 */
public class HashMapDemo {
    public static void main(String[] args) {

        Map<String,String> map = new HashMap<String,String>();

        map.put("c","x993kadsf");
        map.put("d","d993kadsf");
        map.put("a","z993kadsf");
        map.put("f","f993kadsf");
        map.put("b","b993kadsf");

        List<Map.Entry<String,String>> list = new ArrayList<Map.Entry<String,String>>(map.entrySet());
        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return o1.getValue().compareTo(o2.getValue());
            }
        });

        for (Map.Entry<String, String> mapping : list) {
            System.out.println(mapping.getKey() + " : " + mapping.getValue());
        }

        System.out.println(">>>>>>>>>>>>>>> 以下是依据key进行的排序 >>>>>>>>>>>>>>>>>>");

        Collections.sort(list, new Comparator<Map.Entry<String, String>>() {
            @Override
            public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
                return o1.getKey().compareTo(o2.getKey());
            }
        });

        for (Map.Entry<String, String> mapping : list) {
            System.out.println(mapping.getKey() + " : " + mapping.getValue());
        }

        System.out.println(">>>>>>>>>>>>> 使用lamda >>>>>>>>>>>>>>");

        final Map<String, String> sortedByCount2 = map.entrySet()
                .stream()
                .sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));


    }
}
